import React, { useEffect, useRef, useState } from "react";
import useSocket from "../hooks/useSocket";
import { Button, Form, Input, Modal } from "antd";
import "./user.css";
import { useForm } from "antd/es/form/Form";

function Role() {
  const [form] = useForm();
  const arrIcon = ["😊", "🤭", "😄", "😔", "😮", "😱", "😟", "😭", "😀"];
  const [flag, setFlag] = useState(false);
  const user_id = "978";
  const [list, setList] = useState([]);
  const { connectSocket, wsRef } = useSocket(user_id);
  const divRef = useRef(null);
  const connect = () => {
    connectSocket();
    wsRef.current.onopen = () => {
      console.log("连接成功");
      wsRef.current.send(JSON.stringify({ type: "getChatList" }));
      headbeat();
    };
    wsRef.current.onmessage = (e) => {
      // console.log(JSON.parse(e.data));
      const { type, data } = JSON.parse(e.data);
      if (type == "getChatList") {
        // wsRef.current.send(JSON.stringify({ type: 'getChatList' }));
        setList(data);
        setTimeout(() => {
          divRef.current.scrollTop = 9999999;
        }, 0);
      } else if (type == "addMessage") {
        wsRef.current.send(
          JSON.stringify({
            type: "getChatList",
          })
        );
      } else if (type == "heartbeat") {
        localStorage.setItem("heartbeat", Date.now());
      }
    };
    wsRef.current.onerror = () => {};
    wsRef.current.oncolse = () => {};
  };
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const headbeat = () => {
    ref1.current = setInterval(() => {
      wsRef.current.send(JSON.stringify({ type: "heartbeat" }));
    }, 1000);
    ref2.current = setInterval(() => {
      const time = localStorage.getItem("heartbeat");
      const now = Date.now();
      if (now - time > 5000) {
        Modal.error({ title: "连接断开" });
        wsRef.current.close();
        connect();
      }
    }, 10000);
  };

  useEffect(() => {
    connect();
    return () => {
      clearInterval(ref1.current);
      clearInterval(ref2.current);
    };
  }, []);
  const onFinish = (values) => {
    if (!values.text) {
      Modal.error({ title: "不能为空" });
      return;
    }
    wsRef.current.send(
      JSON.stringify({
        type: "addMessage",
        data: { message: values.text, type: "text" },
      })
    );
    form.resetFields();
  };
  const sendEmo = (val) => {
    wsRef.current.send(
      JSON.stringify({
        type: "addMessage",
        data: { message: val, type: "text" },
      })
    );
  };
  return (
    <div className="box1">
      <div className="topfun" ref={divRef}>
        {list.map((item) => {
          if (item.user_id == user_id) {
            return (
              <div className="list1" key={item.id}>
                <img className="img1" src={item.user_avatar} alt="" />
                <p>{item.message}</p>
              </div>
            );
          } else {
            return (
              <div className="list2" key={item.id}>
                <img className="img1" src={item.other_avatar} alt="" />
                <p>{item.message}</p>
              </div>
            );
          }
        })}
      </div>

      <div className="footer">
        <Form onFinish={onFinish} layout="inline" form={form}>
          <Form.Item name="text">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit">发送</Button>
            <Button
              onClick={() => {
                setFlag(!flag);
              }}
            >
              😄
            </Button>
          </Form.Item>
        </Form>
        <div style={{ display: flag ? "block" : "none" }}>
          {arrIcon.map((item, index) => {
            return (
              <span
                key={index}
                onClick={() => {
                  console.log(item);
                  sendEmo(item);
                }}
              >
                {item}
              </span>
            );
          })}
        </div>
      </div>
    </div>
  );
}

export default Role;
